package cn.iocoder.mall.order.biz.aspect;

import cn.iocoder.common.framework.exception.ServiceException;
import cn.iocoder.common.utils.common.system.util.JwtUtil;
import cn.iocoder.common.utils.common.system.vo.UserInfo;
import cn.iocoder.mall.order.biz.utils.RedisUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class IdempotenceOperationAspect {

    @Autowired
    RedisUtil redisUtil;

    @Pointcut("@annotation(cn.iocoder.common.utils.common.annotation.IdempOpta)")
    public void IdempotenceOperation() {

    }


    @Around("IdempotenceOperation()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        //执行方法
        Object result = point.proceed();
        //执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;


        return result;
    }
    @Before("IdempotenceOperation()")
    public void doHandler(JoinPoint joinPoint) throws Exception {
        UserInfo userInfo = JwtUtil.getUserInfoByToken();
        Object seq=redisUtil.getSeq(userInfo.getUserId());
        if (seq!=null&&!seq.equals("0")){
            throw new ServiceException(111111111,"不允许重复操作");
        }
        redisUtil.setSeq(userInfo.getUserId(),"1");

    }

    @AfterReturning("IdempotenceOperation()")
    public void doAfterReturning(){
        UserInfo userInfo = JwtUtil.getUserInfoByToken();
        redisUtil.setSeq(userInfo.getUserId(),"0");
    }

    @AfterThrowing("IdempotenceOperation()")
    public void doAfterThrowing(){
        UserInfo userInfo = JwtUtil.getUserInfoByToken();
        redisUtil.setSeq(userInfo.getUserId(),"0");
    }

}
